<template>
  <div class="dashboard-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总订单数</span>
              <el-icon><el-icon-tickets /></el-icon>
            </div>
          </template>
          <div class="card-content">
            <h2>{{ loading ? '加载中...' : statistics.totalOrderCount }}</h2>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总销售额</span>
              <el-icon><el-icon-money /></el-icon>
            </div>
          </template>
          <div class="card-content">
            <h2>{{ loading ? '加载中...' : `¥${statistics.totalSales?.toFixed(2) || '0.00'}` }}</h2>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>商品总数</span>
              <el-icon><el-icon-goods /></el-icon>
            </div>
          </template>
          <div class="card-content">
            <h2>{{ loading ? '加载中...' : statistics.totalProductCount }}</h2>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活跃用户</span>
              <el-icon><el-icon-user /></el-icon>
            </div>
          </template>
          <div class="card-content">
            <h2>{{ loading ? '加载中...' : userAnalysis.activeUserCount }}</h2>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>近7天销售额</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading">
            <div ref="salesChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading">
            <div ref="orderStatusChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热销商品 -->
    <el-card shadow="hover" class="hot-products-card">
      <template #header>
        <div class="card-header">
          <span>热销商品TOP5</span>
        </div>
      </template>
      <el-table :data="statistics.hotProducts || []" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="sales" label="销量" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="goToProductDetail(scope.row.id)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getStatistics, getUserAnalysis } from '@/api/merchant'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const router = useRouter()
const loading = ref(true)

// 图表引用
const salesChartRef = ref<HTMLElement | null>(null)
const orderStatusChartRef = ref<HTMLElement | null>(null)
let salesChart: echarts.ECharts | null = null
let orderStatusChart: echarts.ECharts | null = null

// 统计数据
const statistics = reactive({
  totalOrderCount: 0,
  totalSales: 0,
  totalProductCount: 0,
  salesLast7Days: [] as any[],
  orderStatusCount: {} as Record<string, number>,
  hotProducts: [] as any[]
})

// 用户分析数据
const userAnalysis = reactive({
  totalUserCount: 0,
  activeUserCount: 0
})

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await getStatistics({})
    if (response.data.code === 200) {
      Object.assign(statistics, response.data.data)
      renderCharts()
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取用户分析数据
const fetchUserAnalysis = async () => {
  try {
    const response = await getUserAnalysis({})
    if (response.data.code === 200) {
      Object.assign(userAnalysis, response.data.data)
    }
  } catch (error) {
    console.error('获取用户分析数据失败:', error)
    ElMessage.error('获取用户分析数据失败')
  } finally {
    loading.value = false
  }
}

// 渲染图表
const renderCharts = () => {
  nextTick(() => {
    // 销售额图表
    if (salesChartRef.value) {
      salesChart = echarts.init(salesChartRef.value)
      const salesOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: statistics.salesLast7Days.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: statistics.salesLast7Days.map(item => item.sales),
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      salesChart.setOption(salesOption)
    }

    // 订单状态图表
    if (orderStatusChartRef.value && statistics.orderStatusCount) {
      orderStatusChart = echarts.init(orderStatusChartRef.value)
      const statusData = Object.entries(statistics.orderStatusCount).map(([name, value]) => ({ name, value }))
      const orderStatusOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: statusData.map(item => item.name)
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: statusData
          }
        ]
      }
      orderStatusChart.setOption(orderStatusOption)
    }
  })
}

// 跳转到商品详情
const goToProductDetail = (id: number) => {
  router.push(`/merchant/products?id=${id}`)
}

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([fetchStatistics(), fetchUserAnalysis()])

  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', () => {
    salesChart?.resize()
    orderStatusChart?.resize()
  })
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
}

h2 {
  margin: 10px 0;
  font-size: 24px;
  color: #409EFF;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.hot-products-card {
  margin-top: 20px;
}
</style>
